import java.util.HashMap;

/**
* @description: 904. 水果成篮
* @author hewei
* @date 2022/9/16 15:49
* @version 1.0
*/

public class TotalFruit {

    public int totalFruit(int[] fruits) {
        int l = 0;
        int r = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        int ans = 0;
        while (r < fruits.length) {
            map.put(fruits[r], map.getOrDefault(fruits[r], 0) + 1);
            if (map.size() > 2) {
                map.put(fruits[l], map.get(fruits[l]) - 1);
                if (map.get(fruits[l]) == 0) map.remove(fruits[l]);
                ++l;
            } else ans = r - l + 1;
            ++r;
        }
        return ans;
    }
}
